'use strict';

angular.module('memoriesApp')
.controller('PhotoDetailCtrl', function($scope, $timeout, $state, $stateParams, $ionicModal, global, photoService, dataStoreFactory) {

  var photoStore = dataStoreFactory.get('photo');
  var photoId, photoUri;

  // Load the modal from the given template URL
  $ionicModal.fromTemplateUrl('views/modal-delete.html', function(modal) {
    $scope.modal = modal;
  }, {
    // Use our scope for the scope of the modal to keep it simple
    scope: $scope,
    // The animation we want to use for the modal entrance
    animation: 'slide-in-up'
  });

  function confirmDelete() {
    if (photoId && photoUri) {
      photoStore.remove(photoId, function() {
        photoService.deletePhoto(photoUri, function() {
          $scope.modal.hide();
          $state.go('tabs.photo-list');
        });
      });
    }
  }

  function deletePhoto() {
    if (photoId && photoUri) {
      $scope.modal.show();
    }
  }

  function init() {
    $scope.vm = {};
    $scope.confirmDelete = confirmDelete;
    $scope.deletePhoto = deletePhoto;

    $scope.closeModal = function() {
      $scope.modal.hide();
    };

   //Be sure to cleanup the modal
    $scope.$on('$destroy', function() {
      $scope.modal.remove();
    });

    photoId = $stateParams.photoId;
    if (photoId) {
      photoStore.getItem(photoId, function(err, data) {
        if (err) return;
        $timeout(function() {
          photoUri = data.uri;
          $scope.vm.photo = data;
        })
      });
    }
  }

  init();

});